package com.gxgeek.apigateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 限流
 * @author gaoxing
 * @create 2018-04-02 上午10:22
 */
@Component
public class RateLimitFilter extends ZuulFilter{
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //FilterConstants.SERVLET_DETECTION_FILTER_ORDER  是最小的 比最小还要小
        return FilterConstants.SERVLET_DETECTION_FILTER_ORDER -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        if (!RATE_LIMITER.tryAcquire()){
//            RequestContext requestContext = RequestContext.getCurrentContext();
//            HttpServletRequest request  =requestContext.getRequest();
            throw new RuntimeException("访问过快");
        }
        return null;
    }
}
